package org.csu.demo.interceptors;


import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.csu.demo.common.CommonResponse;
import org.csu.demo.service.RecordService;
import org.csu.demo.service.impl.OrderServiceImpl;
import org.csu.demo.util.JwtUtil;
import org.csu.demo.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.ContentCachingResponseWrapper;


import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    RecordService recordService;
    @Autowired
    private OrderServiceImpl orderService;


    //创建拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        String URL = request.getServletPath();
        String Method = request.getMethod();
        System.out.println(URL);
        System.out.println(Method);
        // 判断是否为users下的GET请求
        if ("/users".equals(URL) && "POST".equals(Method)) {
            // 不拦截
            return true;
        }
        try {
            Map<String,Object> claims = JwtUtil.parseToken(token);
            //将数据存储在ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除ThreadLocal中的数据
        ThreadLocalUtil.remove();
        orderService.clearlineItemVos();




    }
}
